package com.jmu.shoppingcart;

import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class Cart {
    private BigDecimal totalPrice = new BigDecimal("1");
    public Map<Commodity, Integer> cart = new HashMap<>();
    public Cart() {

    }

    @Override
    public String toString() {
        return cart + "";

    }

    public boolean updateNumber(Commodity commodity, int number) {
        if (cart.get(commodity) < number) {
            return false;
        } else if (number == 0) {
            cart.remove(commodity);
            return true;
        }
        cart.put(commodity, number);
        return true;
    }

    public void add(Commodity goods, int number) {
        if(cart.containsKey(goods)){
            cart.put(goods, cart.get(goods)+number);
        }else {
            cart.put(goods, number);
        }
    }



    public BigDecimal price() {
        if (cart.isEmpty()) {
            return new BigDecimal("0");
        }
        totalPrice = new BigDecimal("0");
        cart.forEach((K, V) -> {
            BigDecimal k = new BigDecimal(K.getPrice() + "");
            BigDecimal v = new BigDecimal(V + "");
            BigDecimal temp1 = k.multiply(v);
            totalPrice = totalPrice.add(temp1);
            //System.out.println(totalPrice);
        });
        return totalPrice;
    }

    public Commodity findCommodity(String name) {
        for (Commodity commodity : cart.keySet()) {
            if (commodity.getName().equals(name)) {
                return commodity;
            }
        }
        return null;
    }
    public void showCart() {
        System.out.println("===============您的购物车=============");
        System.out.println("ID\t\t\tname\t\t\t\tprice\t\t\t\tnumber");
        cart.forEach((K,V)-> System.out.println(K+"\t"+V));
    }
    public void submitOrder() throws IOException {
        Writer fw =new FileWriter("src/com/jmu/shoppingcart/order.txt");
        cart.forEach((K,V)->{
            try {
                fw.write(K.toString()+V+"\n");
            } catch (IOException e) {
                System.out.println(e);
            }
        });
        fw.flush();
    }

    public Commodity getCommdityByName(String name) {
        for (Commodity commodity : cart.keySet()) {
            if(commodity.getName().equals(name)){
                return commodity;
            }
        }
        return null;
    }

    public void delete(Commodity commodity) {
        cart.remove(commodity);
    }
}
